package cn.kvchoi.reactor_nio.server.handlers;

import cn.kvchoi.reactor_nio.server.EventHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class WriteEventHandler implements EventHandler
{

    @Override
    public void handleEvent(SelectionKey key)
    {  
        System.out.println(Thread.currentThread().getName() + ": Write event handler");
        try {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.wrap("bye bye".getBytes(StandardCharsets.UTF_8));
            while (byteBuffer.hasRemaining()) {
                socketChannel.write(byteBuffer);
            }
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("=============");
    }  
  
} 